package org.hsc.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hsc.common.ToBeanResultTransformer;
import org.hsc.model.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleDAO {
	@Autowired private SessionFactory sessionFactory;

	public void add(Article art) {
		sessionFactory.getCurrentSession().save(art);
	}
	
	public void update(Article art) {
		Session  session=sessionFactory.getCurrentSession();
		session.update(art);
		session.flush();
	}
	
	
	public Article get(Long id) {
		return (Article) sessionFactory.getCurrentSession().get(Article.class,id);
	}

	/**
	 * @param id
	 * @return
	 */
	public List<Article> getSub(Long id) {
		Session  session=sessionFactory.getCurrentSession();
		SQLQuery  query=session.createSQLQuery("select ID,TITLE from T_ARTICLE"+(id==null?"":" where parent=:id "));
		if(id!=null){
			query.setParameter("id", id);
		}
		
		Query rq=query.setResultTransformer(ToBeanResultTransformer.aliase(Article.class));
		return rq.list();
	}

	/**
	 * @return
	 */
	public List<Article> getNvg() {
		Session  session=sessionFactory.getCurrentSession();
		SQLQuery  sq=session.createSQLQuery("select ID,TITLE,PARENT from T_ARTICLE");
		Query rq=sq.setResultTransformer(ToBeanResultTransformer.aliase(Article.class));
		return rq.list();
	}

	public void delete(Long id) {
		Query query=sessionFactory.getCurrentSession().createQuery("delete Article where id=:id ");
		query.setParameter("id", id);
	
		query.executeUpdate();
	}
	
}
